package org.liuwei.concurent04.CurrentLimit01;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

//限流某个接口的总并发/请求数
public class CurrentLimit {
	static AtomicInteger atomic = new AtomicInteger();
	private static int limit = 1;// 限流数

	public static void main(String[] args) {
		Thread t1 = new Thread(new AddTask(), "t1");
		Thread t2 = new Thread(new AddTask(), "t2");
		Thread t3 = new Thread(new AddTask(), "t3");
		Thread t4 = new Thread(new AddTask(), "t3");
		Thread t5 = new Thread(new AddTask(), "t3");
		t1.start();
		t2.start();
		t3.start();
		t4.start();
		t5.start();
	}

	public static void limit() throws InterruptedException {
		try {
			if (atomic.incrementAndGet() > limit) {
				// 拒绝请求
				System.out.println("此次请求拒绝了");
				return;
			}
			exe();
			// 处理请求
		} finally {
			atomic.decrementAndGet();
		}

	}

	public static void exe() throws InterruptedException {
		TimeUnit.SECONDS.sleep(1);
		System.out.println("我执行了！");
	}
}

class AddTask implements Runnable {
	public void run() {
		try {
			CurrentLimit.limit();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}
}
